package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	//相对时间
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
	//绝对时间，必须是当前时间后
	//ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*3))
	go doSome(ctx)
	defer cancel()
	time.Sleep(time.Second*5)
}

func doSome(ctx context.Context) {
	for {
		time.Sleep(time.Second)
		select {
		case <-ctx.Done():
			fmt.Println("Done")
			return
		default:
			fmt.Printf("doSomething\n")
		}
	}
}